const { pool } = require("../../db");

const {
  processedData,
  processMedia,
  processCommentData,
  processMapData,
} = require("./processData");
const { convertToObjectArray } = require("./utils");
/**
 *  用户登录
 * @param {*} body
 * @param {*} openid
 * @param {*} session_key
 * @returns
 */
exports.userLogin = async (body, openid, session_key) => {
  let userInfo = JSON.parse(body.rawData);
  const checkUser = `SELECT * FROM user WHERE user_id='${openid}'`;
  const addUser = `INSERT INTO user (user_id,nickname,avatar,gender) VALUES ('${openid}','${userInfo.nickName}','${userInfo.avatarUrl}',${userInfo.gender})`;

  try {
    const [results] = await pool.query(checkUser);
    if (results.length > 0) {
      return {
        code: 200,
        message: "登录成功",
        ok: true,
        data: {
          userInfo: results[0],
          session_key,
        },
      };
    } else {
      const [results] = await pool.query(addUser);
      if (results.affectedRows > 0) {
        return {
          code: 200,
          message: "登录成功",
          ok: true,
          data: {
            userInfo: results.insertId,
            session_key,
          },
        };
      } else {
        return {
          code: 400,
          message: "登录失败",
          ok: false,
        };
      }
    }
  } catch (error) {
    return { code: 500, message: "服务器错误1" + error, ok: false };
  }
};
/**
 *  获取用户信息
 * @returns
 */
exports.getUserInfo = async (userId) => {
  const getUserInfoSql = `SELECT * FROM user WHERE user_id='${userId}'`;
  try {
    const [results] = await pool.query(getUserInfoSql);
    if (results.length > 0) {
      return {
        code: 200,
        message: "获取用户信息成功",
        ok: true,
        data: results[0],
      };
    } else {
      return {
        code: 400,
        message: "获取用户信息失败",
        ok: false,
      };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误2" + error, ok: false };
  }
};

/**
 *  更新用户信息
 * @param {*} userId
 * @param {*} nickname
 * @param {*} phone
 * @param {*} avatar
 * @returns
 */
exports.updateUserInfo = async (
  userId,
  nickname = null,
  phone = null,
  avatar = null,
  gender = null
) => {
  // 构建动态 SET 子句，处理 null 值
  let setClause = "";
  if (nickname !== null) {
    setClause += "nickname='" + nickname + "', ";
  }
  if (phone !== null) {
    setClause += "phone='" + phone + "', ";
  }
  if (avatar !== null) {
    setClause += "avatar='" + avatar + "', ";
  }
  if (gender !== null) {
    setClause += "gender='" + gender + "', ";
  }
  // 移除末尾的逗号
  setClause = setClause.slice(0, -2);

  // 构建完整的 SQL 更新语句
  const updateUserInfoSql = `UPDATE user SET ${setClause} WHERE user_id=?`;
  try {
    const [results] = await pool.query(updateUserInfoSql, [userId]);
    if (results.affectedRows > 0) {
      return { code: 200, message: "更新成功", ok: true };
    } else {
      return { code: 400, message: "更新失败", ok: false };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};
/**
 *  获取首页推荐数据
 * @param {*} location 经纬度
 * @param {*} distance 距离（默认值为2，单位公里）
 * @returns =
 */
exports.getData = async (location, distance = 2) => {
  const { longitude, latitude } = location;

  const sql = `
  SELECT
  f.*,
  m.id AS media_id,
  m.name AS media_name,
  m.uid AS media_uid,
  m.type AS media_type,
  m.path AS media_path,
  m.imgUrl AS media_imgUrl,
  m.is_cover AS media_is_cover,
  m.food_id AS media_food_id,
  m.travel_id AS media_travel_id,
  m.is_show AS media_is_show,
  m.createTime AS media_createTime,
  m.updateTime AS media_updateTime,
  'food' AS type
FROM
  food AS f
  INNER JOIN media AS m ON f.id = m.food_id
  AND ST_Distance_Sphere(Point(f.longitude, f.latitude), Point(${longitude}, ${latitude})) <= ${
    distance * 1000
  }
WHERE
  m.is_show = 1
  AND m.is_cover = 1

UNION

SELECT
  t.*,
  m.id AS media_id,
  m.name AS media_name,
  m.uid AS media_uid,
  m.type AS media_type,
  m.path AS media_path,
  m.imgUrl AS media_imgUrl,
  m.is_cover AS media_is_cover,
  m.food_id AS media_food_id,
  m.travel_id AS media_travel_id,
  m.is_show AS media_is_show,
  m.createTime AS media_createTime,
  m.updateTime AS media_updateTime,
  'travel' AS type
FROM
  travel AS t
  INNER JOIN media AS m ON t.id = m.travel_id
  AND ST_Distance_Sphere(Point(t.longitude, t.latitude), Point(${longitude}, ${latitude})) <= ${
    distance * 1000
  }
WHERE
  m.is_show = 1
  AND m.is_cover = 1;
`;

  try {
    const [rows] = await pool.query(sql);

    let data = processedData(rows);
    data = convertToObjectArray(data);
    return {
      code: 200,
      data,
      ok: true,
    };
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误" + error,
      ok: false,
    };
  }
};
/**
 * 获取热门数据
 * @param {*} limit 每次获取数量
 * @param {*} offset 偏移量
 * @returns
 */
exports.getHotData = async (limit, offset) => {
  const sql = `(SELECT f.*, m.id AS media_id, m.name AS media_name, m.uid AS media_uid, m.type AS media_type, m.path AS media_path, m.imgUrl AS media_imgUrl, m.is_cover AS media_is_cover, m.food_id AS media_food_id, m.travel_id AS media_travel_id, m.is_show AS media_is_show, m.createTime AS media_createTime, m.updateTime AS media_updateTime, 'food' AS type FROM food AS f LEFT JOIN media AS m ON f.id = m.food_id WHERE m.is_show = 1 AND m.is_cover = 1 ORDER BY f.rating DESC)
  UNION ALL
  (SELECT t.*, m.id AS media_id, m.name AS media_name, m.uid AS media_uid, m.type AS media_type, m.path AS media_path, m.imgUrl AS media_imgUrl, m.is_cover AS media_is_cover, m.food_id AS media_food_id, m.travel_id AS media_travel_id, m.is_show AS media_is_show, m.createTime AS media_createTime, m.updateTime AS media_updateTime, 'travel' AS type FROM travel AS t LEFT JOIN media AS m ON t.id = m.travel_id WHERE m.is_show = 1 AND m.is_cover = 1 ORDER BY t.rating DESC)
  ORDER BY rating DESC;`;

  try {
    const [rows] = await pool.query(sql);

    let data = processedData(rows);
    data = convertToObjectArray(data);
    let pages = Math.floor(data.length / limit);

    // 分页处理
    const paginatedData = data.slice(offset, offset + limit);

    return {
      code: 200,
      data: paginatedData,
      pages,
      ok: true,
    };
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误" + error,
      ok: false,
    };
  }
};

/**
 *
 * @param {*} type 表名
 * @param {*} id
 * @returns
 */
exports.getDetail = async (type, id) => {
  const sql = `SELECT *,'${type}' as type FROM ${type}  WHERE id = ${id}`;

  try {
    let [rows] = await pool.query(sql);
    if (rows.length > 0) {
      let data = rows[0];
      const mediaSql = `SELECT * FROM media WHERE ${type}_id = ${id} AND is_show = 1`;
      let [mediaRows] = await pool.query(mediaSql);

      data.media = processMedia(mediaRows);

      return {
        code: 200,
        data,
        ok: true,
      };
    } else {
      return {
        code: 500,
        message: "数据不存在",
        ok: false,
      };
    }
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误" + error,
      ok: false,
    };
  }
};
/**
 * 获取用户端总览的数据
 * @param {String} type 选择表
 * @param {String} location 地点
 * @param {Number} limit 限制条数
 * @param {Number} offset 偏移量
 * @returns
 */
exports.getListData = async (type, location, limit, offset) => {
  const sql = `SELECT
  ${type}.*,
  m.id AS media_id,
  m.name AS media_name,
  m.uid AS media_uid,
  m.type AS media_type,
  m.path AS media_path,
  m.imgUrl AS media_imgUrl,
  m.is_cover AS media_is_cover,
  m.food_id AS media_food_id,
  m.travel_id AS media_travel_id,
  m.is_show AS media_is_show,
  m.createTime AS media_createTime,
  m.updateTime AS media_updateTime,
  '${type}' AS type
FROM
  (SELECT * FROM ${type} WHERE location LIKE '%${location}%' LIMIT ${offset}, ${limit}) AS ${type}
  INNER JOIN media AS m ON ${type}.id = m.${type}_id
WHERE
  m.is_show = 1
  AND m.is_cover = 1;`;
  const countSql = `SELECT COUNT(*) AS count FROM ${type} WHERE location LIKE '%${location}%'`;
  try {
    const [results] = await pool.query(sql);
    const [countResults] = await pool.query(countSql);
    totalRecords = countResults[0].count;

    let data = convertToObjectArray(processedData(results));
    if (results.length > 0) {
      return {
        code: 200,
        message: "获取数据成功",
        ok: true,
        data,
        pages: Math.ceil(totalRecords / limit),
      };
    } else {
      return {
        code: 500,
        message: "获取数据失败",
        ok: false,
        data: [],
        pages: 0,
      };
    }
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误" + error,
      ok: false,
    };
  }
};

/**
 * 获取用户端评论数据
 * @param {*} limit
 * @param {*} offset
 * @returns
 */
exports.getCommentData = async (
  limit,
  offset,
  userId = "",
  type,
  typeId = ""
) => {
  let sql = "";
  let sqlCount = "";
  let joinClause = "";
  let whereClause = "c.is_online = 1 and c.parent_id is NULL";
  let totalRecords = 0; // 总记录数
  // 构建用于计算总记录数的 SQL 语句
  sqlCount = `SELECT COUNT(*) AS count FROM comment AS c WHERE ${whereClause}`;
  if (userId) {
    whereClause += " AND user_id = ?";
  } else if (typeId > 0) {
    whereClause += ` AND ${type}_id = ?`;
  }

  // 执行查询以获取总记录数
  try {
    const [countResults] = await pool.query(sqlCount, [
      ...(userId ? [userId] : []),
      ...(typeId > 0 ? [typeId] : []),
    ]);
    totalRecords = countResults[0].count;
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误获取总记录数",
      ok: false,
    };
  }

  // 根据 userId 和 typeId 的存在与否构建不同的 SQL 语句
  let params = [...(userId ? [userId] : []), ...(typeId > 0 ? [typeId] : [])];
  if (userId) {
    // 当有 userId 时，不需要联查 user 表
    sql = `SELECT * FROM comment as c WHERE ${whereClause} AND user_id = ? LIMIT ?, ?`;
    console.log(111);
  } else if (typeId > 0) {
    // 当有 typeId 时，需要联查 user 表，并且 comment 要对应的 ${type}_id

    joinClause = "LEFT JOIN user AS usr ON c.user_id = usr.user_id";
    sql = `SELECT c.id, c.user_id, c.parent_id, c.food_id, c.travel_id, c.content, c.rating, c.media_urls, c.createTime, usr.id as usr_id, usr.username, usr.nickname, usr.avatar FROM comment AS c ${joinClause} WHERE ${whereClause} ORDER BY c.createTime DESC LIMIT ?, ? `;
  } else {
    // 当两者都没有时，联查 user 表
    joinClause = "LEFT JOIN user AS usr ON c.user_id = usr.user_id";
    sql = `SELECT c.id, c.user_id, c.parent_id, c.food_id, c.travel_id, c.content, c.rating, c.media_urls, c.createTime, usr.id as usr_id, usr.username, usr.nickname, usr.avatar FROM comment AS c ${joinClause} WHERE ${whereClause} ORDER BY c.createTime DESC LIMIT ?, ? `;
  }

  try {
    const [results] = await pool.query(sql, params.concat(offset, limit));
    const commentsWithUsers = await Promise.all(
      results.map(async (comment) => {
        // 递归获取每个评论的子评论
        const children = await getChildrenComments(comment.id);
        return {
          ...comment,
          user: comment.usr_id
            ? {
                ...comment,
                ...{
                  username: comment.usr_username,
                  nickname: comment.usr_nickname,
                  avatar: comment.usr_avatar,
                },
              }
            : await getUserById(comment.user_id),
          children, // 添加子评论数组
        };
      })
    );

    // 计算总页数
    const totalPages = Math.ceil(totalRecords / limit);
    return {
      code: 200,
      message: "获取数据成功",
      ok: true,
      data: commentsWithUsers, // 返回包含子评论和用户信息的评论数组
      pages: totalPages,
    };
  } catch (error) {
    console.log(error);
    return { code: 500, message: error, ok: false };
  }
};

// 递归函数：获取评论的所有子评论
const getChildrenComments = async (parentId) => {
  const [childrenRows] = await pool.query(
    "SELECT * FROM comment WHERE parent_id = ?",
    [parentId]
  );
  return await Promise.all(
    childrenRows.map(async (childRow) => {
      const grandChildren = await getChildrenComments(childRow.id);
      return {
        ...childRow,
        user: await getUserById(childRow.user_id), // 获取子评论的用户信息
        children: grandChildren, // 添加子评论数组
      };
    })
  );
};

// 辅助函数：根据用户 ID 获取用户数据
const getUserById = async (userId) => {
  try {
    const [userResults] = await pool.query(
      "SELECT username, nickname, avatar FROM user WHERE user_id = ?",
      [userId]
    );
    return userResults[0];
  } catch (error) {
    console.error(error);
    throw new Error("获取用户信息失败");
  }
};

/**
 *  获取用户评论
 * @param {*} userId
 * @param {*} offset
 * @param {*} limit
 * @returns
 */
exports.getUserComment = async (userId, offset, limit) => {
  let sql = `select * from comment where user_id='${userId}' LIMIT ${offset},${limit}`;
  let countSql = `select count(*) as count from comment where user_id='${userId}'`;
  try {
    const [results] = await pool.query(sql, [userId, offset, limit]);
    const [count] = await pool.query(countSql, [userId]);
    const totalRecords = Math.floor(count[0].count / limit);
    if (results.length > 0) {
      return {
        code: 200,
        message: "获取数据成功",
        ok: true,
        data: results,
        pages: totalRecords,
      };
    } else {
      return { code: 400, message: "获取数据失败", ok: false };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};
/**
 *  添加评论
 * @param {*} userId
 * @param {*} comment
 * @param {*} rate
 * @param {*} type
 * @param {*} id
 * @param {*} image
 * @returns
 */
exports.addComment = async (userId, comment, rate, type, id, image) => {
  let sqlInsert = `INSERT INTO comment (user_id, content, rating, ${type}_id, media_urls) VALUES ('${userId}', '${comment}', ${rate}, ${id}, '${image}')`;
  let sqlUpdate = `UPDATE ${type} SET rating = ? WHERE id = ?;`;
  try {
    // 插入评论
    await pool.query(sqlInsert);
    // 计算总和和平均值
    let sqlSum = `SELECT SUM(rating) AS total_rating FROM comment WHERE ${type}_id = ?;`;
    let [sumResults] = await pool.query(sqlSum, [id]);
    const totalRating = sumResults[0].total_rating || 0;

    let sqlCount = `SELECT COUNT(*) AS count FROM comment WHERE ${type}_id = ?;`;
    let [countResults] = await pool.query(sqlCount, [id]);
    const count = countResults[0].count || 1;
    // 确保至少有一个评论，避免除以0
    // 计算平均值
    const averageRating = (totalRating / count).toFixed(2); // 保留两位小数
    // 更新 food 或 travel 表
    await pool.query(sqlUpdate, [averageRating, id]);
    return { code: 200, message: "评论成功", ok: true };
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};
/**
 * @api {post} /addRecoverComment 添加回复评论
 *
 */

exports.addRecoverComment = async (content, userId, parentId) => {
  let sqlInsert = `INSERT INTO comment (user_id, content,  parent_id,is_online) VALUES ('${userId}', '${content}',  ${parentId},1)`;
  try {
    let [results] = await pool.query(sqlInsert);
    //  通过results的user_id联查user表返回comment数据以及user数据
    let userSql = `SELECT u.id,u.nickname,u.avatar,c.id AS comment_id,c.content,c.createTime,c.parent_id,c.is_online,c.user_id FROM user u LEFT JOIN comment c ON u.user_id = c.user_id WHERE c.id = ${results.insertId}`;
    let [userResults] = await pool.query(userSql);

    return { code: 200, data: userResults[0], message: "回复成功", ok: true };
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};
/**
 * 获取地图模块数据
 * @param {*} limit
 * @param {*} offset
 * @param {*} location
 * @param {*} type
 * @param {*} distance
 * @returns
 */
exports.getMapData = async (location, type = "food", distance = 50) => {
  const { longitude, latitude } = location;

  const sql = `SELECT
  ${type}.*,
  m.id AS media_id,
  m.name AS media_name,
  m.uid AS media_uid,
  m.type AS media_type,
  m.path AS media_path,
  m.imgUrl AS media_imgUrl,
  m.is_cover AS media_is_cover,
  m.food_id AS media_food_id,
  m.travel_id AS media_travel_id,
  m.is_show AS media_is_show,
  m.createTime AS media_createTime,
  m.updateTime AS media_updateTime,
  '${type}' AS type
FROM
  ${type}
  INNER JOIN media AS m ON ${type}.id = m.${type}_id
  AND ST_Distance_Sphere(Point(${type}.longitude, ${type}.latitude), Point(?, ?)) <= ${
    distance * 1000
  }
WHERE
  m.is_show = 1
  AND m.is_cover = 1`;

  try {
    const [results] = await pool.query(sql, [longitude, latitude]);
    let res = processMapData(results);
    if (results.length > 0) {
      return {
        code: 200,
        message: "获取数据成功",
        ok: true,
        data: convertToObjectArray(res),
      };
    } else {
      return {
        code: 400,
        message: "获取数据失败",
        ok: false,
      };
    }
  } catch (error) {
    return {
      code: 500,
      message: "服务器错误" + error,
      ok: false,
    };
  }
};
/**
 *  获取用户收藏数据
 * @param {*} limit
 * @param {*} offset
 * @param {*} userId
 * @param {*} type
 * @returns
 */
exports.getUserFavoriteData = async (limit, offset, userId = "", type = "") => {
  const getTypeIdSql = `Select ${type}_id from favorite where user_id='${userId}' AND ${type}_id is not null`;

  try {
    const [results] = await pool.query(getTypeIdSql);

    if (results.length > 0) {
      const typeIdArr = results.map((item) => item[`${type}_id`]);
      const getTypeDataSql = `SELECT
      ${type}.*,
      m.id AS media_id,
      m.name AS media_name,
      m.uid AS media_uid,
      m.type AS media_type,
      m.path AS media_path,
      m.imgUrl AS media_imgUrl,
      m.is_cover AS media_is_cover,
      m.food_id AS media_food_id,
      m.travel_id AS media_travel_id,
      m.is_show AS media_is_show,
      m.createTime AS media_createTime,
      m.updateTime AS media_updateTime,
      '${type}' AS type
    FROM
      (SELECT * FROM ${type} WHERE id IN (${typeIdArr}) LIMIT ${offset}, ${limit}) AS ${type}
      INNER JOIN media AS m ON ${type}.id = m.${type}_id
    WHERE
      m.is_show = 1
      AND m.is_cover = 1;`;
      const [typeData] = await pool.query(getTypeDataSql);
      let data = convertToObjectArray(processedData(typeData));

      return {
        code: 200,
        message: "获取数据成功",
        ok: true,
        data,
        pages: Math.ceil(results.length / limit),
      };
    } else {
      return {
        code: 400,
        message: "暂无数据",
        ok: false,
      };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error, ok: false };
  }
};

/**
 *  判断用户是否收藏
 * @param {*} userId
 * @param {*} type
 * @param {*} typeId
 * @returns
 */
exports.getHasFav = async (userId, type, typeId) => {
  const getHasFavSql = `SELECT * FROM favorite WHERE user_id=? AND ${type}_id=?`;
  try {
    const [results] = await pool.query(getHasFavSql, [userId, typeId]);
    if (results.length > 0) {
      return {
        code: 200,
        message: "已收藏",
        ok: true,
      };
    } else {
      return {
        code: 400,
        message: "未收藏",
        ok: false,
      };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error, ok: false };
  }
};
/**
 *  添加用户收藏
 * @param {*} userId
 * @param {*} type
 * @param {*} typeId
 * @returns
 */
exports.addFavorite = async (userId, type, typeId) => {
  const addFavoriteSql = `INSERT INTO favorite (user_id,${type}_id) VALUES (?,?)`;

  try {
    const [results] = await pool.query(addFavoriteSql, [userId, typeId]);
    if (results.affectedRows > 0) {
      return {
        code: 200,
        message: "添加成功",
        ok: true,
      };
    } else {
      return {
        code: 400,
        message: "添加失败",
        ok: false,
      };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error, ok: false };
  }
};
/**
 *  删除用户收藏
 * @param {*} userId
 * @param {*} type
 * @param {*} typeId
 * @returns
 */
exports.removeFavorite = async (userId, type, typeId) => {
  const removeFavoriteSql = `DELETE FROM favorite WHERE user_id=? AND ${type}_id=?`;
  try {
    const [results] = await pool.query(removeFavoriteSql, [userId, typeId]);
    if (results.affectedRows > 0) {
      return {
        code: 200,
        message: "删除成功",
        ok: true,
      };
    } else {
      return {
        code: 400,
        message: "删除失败",
        ok: false,
      };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error, ok: false };
  }
};

/**
 *  获取用户反馈
 * @param {*} limit
 * @param {*} offset
 * @param {*} userId
 * @returns
 */
exports.getFeedback = async (limit, offset, userId) => {
  let sql = `select * from feedback where user_id=? ORDER BY create_time DESC limit ?,?`;
  let countSql = `select count(*) as count from feedback where user_id=?`;
  try {
    const [results] = await pool.query(sql, [userId, offset, limit]);
    const [count] = await pool.query(countSql, [userId]);
    const totalRecords = Math.floor(count[0].count / limit);
    if (results.length > 0) {
      return {
        code: 200,
        message: "获取数据成功",
        ok: true,
        data: results,
        pages: totalRecords,
      };
    } else {
      return { code: 400, message: "获取数据失败", ok: false };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};

/**
 *  添加反馈
 * @param {*} content
 * @param {*} people
 * @param {*} contact
 * @param {*} image
 * @param {*} userId
 * @returns
 */

exports.addFeedback = async (content, people, contact, image, userId) => {
  let sql = `insert into feedback(content,contact_name,contact_way,images,user_id) values(?,?,?,?,?)`;
  try {
    const [results] = await pool.query(sql, [
      content,
      people,
      contact,
      image,
      userId,
    ]);
    if (results.affectedRows > 0) {
      return { code: 200, message: "反馈成功", ok: true };
    } else {
      return { code: 400, message: "反馈失败", ok: false };
    }
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};

/**
 * 推荐功能
 * @param {*} recommend
 * @returns
 */
exports.recommentData = async (recommend) => {
  let {
    name,
    price,
    introduction,
    type,
    rate,
    phone,
    is_online,
    location,
    longitude,
    latitude,
    images,
  } = recommend;
  let ty = type == 0 ? "food" : "travel";
  const sql = `INSERT INTO ${ty} (name, price, introduction,  rating, phone, is_online, location, longitude, latitude) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
  try {
    const [results] = await pool.query(sql, [
      name,
      price,
      introduction,
      rate,
      phone,
      is_online,
      location,
      longitude,
      latitude,
    ]);
    if (images.length > 0) {
      for (const item of images) {
        const { type, is_cover, uid, name, path, imgUrl, is_show } = item;
        const imgSql = `INSERT INTO media (type,is_cover,uid,name,path,imgUrl,${ty}_id,is_show) VALUES (?,?,?,?,?,?,?,?)`;
        await pool.execute(imgSql, [
          type,
          is_cover,
          uid,
          name,
          path,
          imgUrl,
          results.insertId,
          is_show,
        ]);
      }
    }
    return { code: 200, message: "添加成功", ok: true };
  } catch (error) {
    return { code: 500, message: "服务器错误" + error.message, ok: false };
  }
};
